package com.vsd.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.demo.util.JSONUtils;
import com.demo.util.MathUtil;
import com.demo.util.StringUtil;
import com.vsd.domain.UserCollect;
import com.vsd.repository.UserCollectionRepository;
import com.vsd.service.UserCollectService;
import com.zy.store.proto.MOAppStore.MStoreMini;
import com.zy.store.proto.MOAppStore.MStoreMiniList;
import com.zy.store.proto.MOAppStore.MTgGoodsMini;
import com.zy.store.proto.MOAppStore.MTgGoodsMiniList;

@Service
@Transactional
public class UserCollectServiceImpl implements UserCollectService {

	@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory
			.getLogger(UserCollectServiceImpl.class);
	
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	@Autowired
	private UserCollectionRepository collectionRepository;

	@Override
	public int isCollect(String userId, Integer type, String fid) {
		// TODO Auto-generated method stub
		return collectionRepository.isCollect(userId, type, fid);
	}
	
	@Override
	public UserCollect save(UserCollect c) {
		// TODO Auto-generated method stub
		return collectionRepository.save(c);
	}
	
	@Override
	public MStoreMiniList.Builder myCollectStore(String userId,String lat,
			String lng, Integer page,Integer limit) {
		// TODO Auto-generated method stub
		String sql = "select s.*,sc.`name` as cateName,ci.`name` as cityName ";
		if(StringUtils.isNoneBlank(lat)&&StringUtils.isNoneBlank(lng)){
			sql+=",getDistance(s.lng,s.lat,"+lng+","+lat+") as distance";
		}	
				
		sql+= ",(select count(1) from s_store_comment sc1 where sc1.store_id = s.id) as commentCnt"
		+ ",(select avg(sc1.score) from s_store_comment sc1 where sc1.store_id = s.id ) as avgScore	"
		+"  from f_user_collect c"
		+ " left join s_store s on c.fid = s.id "
		+" left join s_store_category sc on s.cate_code = sc.`code`	"
		+ " left join f_city ci on s.area_code = ci.`code`	"
		+ " where c.type=2 and s.closed = 0 and s.is_online=1 and c.uid = '"+userId+"' limit "+(page*limit)+","+limit;
		
		MStoreMiniList.Builder ret = MStoreMiniList.newBuilder();
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		for (Map<String, Object> map : maps) {
			MStoreMini.Builder m = MStoreMini.newBuilder();
			m.setCateName(StringUtil.obj2String(map.get("cateName")));
			m.setCityName(StringUtil.obj2String(map.get("cityName")));
			m.setCommentCnt(MathUtil.formatAsComment(StringUtil.obj2String(map.get("commentCnt"))));
			m.setStar(map.get("avgScore")==null?0:new Double(StringUtil.obj2String(map.get("avgScore"))));
			m.setLogo(StringUtil.obj2String(map.get("logo")));
			m.setTitle(StringUtil.obj2String(map.get("name")));
			m.setDistance(MathUtil.getDistanceStr(StringUtil.obj2String(map.get("distance"))));
			m.setId(StringUtil.obj2String(map.get("id")));
			ret.addList(m);
		}
		
		return ret;
	}

	@Override
	public int delByUserIdAndType(String userId, Integer type, String id) {
		String sql = "delete from f_user_collect  where fid ='"+id+"' and type="+type+" and uid='"+userId+"'";
		return jdbcTemplate.update(sql);
	}
	
	
	@Override
	public MTgGoodsMiniList.Builder myCollectGoods(String userId,String lat,
			String lng, Integer page,Integer limit) {
		
		MTgGoodsMiniList.Builder ret = MTgGoodsMiniList.newBuilder();
		
		String sql = "select sg.id as goodsId,sg.`name` as goodsName,sg.img,sg.now_price,sg.sell_base	,s.`name` as storeName ";
		if(StringUtils.isNoneBlank(lat)&&StringUtils.isNoneBlank(lng)){
			sql+=",getDistance(s.lng,s.lat,"+lng+","+lat+") as distance";
		}	
				
		sql+= "	,(select count(1) from s_order o where o.store_id = s.id and o.state=4) as sellCnt"
		+"  from f_user_collect c"
		+ " left join s_store_goods sg on c.fid = sg.id "
		 +"	left join s_store s on s.id = sg.store_id"
		+ " where c.type=1 and s.closed = 0 and s.is_online=1 and c.uid = '"+userId+"' limit "+(page*limit)+","+limit;
		
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		
		for (Map<String, Object> map : maps) {
			MTgGoodsMini.Builder mini = MTgGoodsMini.newBuilder();
			mini.setDistance(MathUtil.getDistanceStr(StringUtil.obj2String(map.get("distance"))));
			mini.setGoodsName(StringUtil.obj2String(map.get("goodsName")));
			mini.setId(StringUtil.obj2String(map.get("goodsId")));
			mini.setImg(StringUtil.obj2String(map.get("img")));
			mini.setPrice(StringUtil.obj2String(map.get("now_price")));
			int sellBase = map.get("sell_base")==null?0:new Integer(map.get("sell_base").toString());
			int sellCnt = map.get("sellCnt")==null?0:new Integer(map.get("sellCnt").toString());
			mini.setSellCnt((sellBase+sellCnt)+"");
			mini.setStoreName(StringUtil.obj2String(map.get("storeName")));
			ret.addList(mini);
		}
		
		
		return ret;
	}
	@Override
	public String collectGoods(String userId, String lat, String lng,
			Integer page, Integer limit) {
		String sql = "select sg.id as goodsId,sg.`name` as goodsName,sg.img,sg.now_price,sg.sell_base	,s.`name` as storeName ";
		if (StringUtils.isNoneBlank(lat) && StringUtils.isNoneBlank(lng)) {
			sql += ",getDistance(s.lng,s.lat," + lng + "," + lat
					+ ") as distance";
		}

		sql += "	,(select count(1) from s_order o where o.store_id = s.id and o.state=4) as sellCnt"
				+ "  from f_user_collect c"
				+ "left join s_store_goods sg on c.fid = sg.id "
				+ "	left join s_store s on s.id = sg.store_id"
				+ "where c.type=1 and s.closed = 0 and s.is_online=1 and c.uid = '"
				+ userId + "' limit " + (page * limit) + "," + limit;

		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		JSONArray ret = new JSONArray();
		for (Map<String, Object> map : maps) {
			JSONObject mini = new JSONObject();
			mini.put("distance", MathUtil.getDistanceStr(StringUtil
					.obj2String(map.get("distance"))));
			mini.put("goodsName", StringUtil.obj2String(map.get("goodsName")));
			mini.put("goodsId", map.get("goodsId"));
			mini.put("img", map.get("img"));
			mini.put("nowPrice", map.get("now_price"));

			int sellBase = map.get("sell_base") == null ? 0 : new Integer(map
					.get("sell_base").toString());
			int sellCnt = map.get("sellCnt") == null ? 0 : new Integer(map.get(
					"sellCnt").toString());

			mini.put("sellCnt", (sellBase + sellCnt) + "");
			mini.put("storeName", map.get("storeName"));

			ret.add(mini);
		}
		return JSONUtils.serialize(ret);
	}
	@Override
	public String collectStore(String userId, String lat, String lng,
			Integer page, Integer limit) {
		// TODO Auto-generated method stub
		String sql = "select s.*,sc.`name` as cateName,ci.`name` as cityName ";
		if (StringUtils.isNoneBlank(lat) && StringUtils.isNoneBlank(lng)) {
			sql += ",getDistance(s.lng,s.lat," + lng + "," + lat
					+ ") as distance";
		}

		sql += ",(select count(1) from s_store_comment sc1 where sc1.store_id = s.id) as commentCnt"
				+ ",(select avg(sc1.score) from s_store_comment sc1 where sc1.store_id = s.id ) as avgScore	"
				+ "  from f_user_collect c"
				+ "left join s_store s on c.fid = s.id "
				+ "left join s_store_category sc on s.cate_code = sc.`code`	"
				+ "left join f_city ci on s.area_code = ci.`code`	"
				+ "where c.type=2 and s.closed = 0 and s.is_online=1 and c.uid = '"
				+ userId + "' limit " + (page * limit) + "," + limit;
		JSONArray ret = new JSONArray();
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		for (Map<String, Object> map : maps) {
			JSONObject m = new JSONObject();
			m.put("cateName", map.get("cateName"));
			m.put("cityName", map.get("cityName"));
			m.put("commentCnt", map.get("commentCnt"));
			m.put("star", map.get("avgScore") == null ? 0 : new Double(StringUtil
					.obj2String(map.get("avgScore"))));
			m.put("logo", map.get("logo"));
			m.put("name", map.get("name"));
			m.put("id", map.get("id"));
			m.put("distance", MathUtil.getDistanceStr(StringUtil.obj2String(map
					.get("distance"))));
			ret.add(m);
		}
		return JSONUtils.serialize(ret);
	}
	 
}
